package com.biwin.core.main.handler;

import com.biwin.common.api.constant.BwSystemConstant;
import com.biwin.common.app.exception.BwBasicException;
import com.biwin.common.app.vo.BwResponse;
import com.biwin.core.api.enums.BwBasicExceptionEnum;
import com.biwin.core.main.property.BiWinProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * BiWin framework Global Exception Handler
 *
 * @author biwin
 * @since 0.0.1
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Autowired
    private BiWinProperties biWinProperties;

    /**
     * 全局的BiWin Exception 处理器
     *
     * @param e {@link BwBasicException}
     * @return
     */
    @ExceptionHandler(BwBasicException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BwResponse bwBasicExceptionHandler(BwBasicException e) {
        log.error("检测到 BiWin 框架异常...");
        Map<String, Object> requestParams = e.getRequestParams();
        //        requestParams.put(BwSystemConstant.CAUSE, ((DataIntegrityViolationException) e)
        //        .getMostSpecificCause().getMessage());
        requestParams.put(BwSystemConstant.TRACE, e.getStackTrace());
        return new BwResponse(e.getErrorCode(), e.getErrorMessage(), requestParams);
    }

    /**
     * 方法参数错误异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BwResponse methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("检测到方法参数校验异常...");
        Map<String, String> validMap = new HashMap<>();
        // 从异常对象中拿到 FieldError 对象
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        if (!fieldErrors.isEmpty()) {
            for (FieldError fieldError : fieldErrors) {
                validMap.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
        }
        // 然后提取错误提示信息进行返回
        return new BwResponse(BwBasicExceptionEnum.VALID_ERROR, validMap);
    }

    @ExceptionHandler(ObjectOptimisticLockingFailureException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BwResponse dataOptimisticLockingExceptionHandler(Exception e) {
        log.error("检测到数据乐观锁异常...");
        Map<String, Object> data = null;
        if (biWinProperties.getDebug()) {
            data = new HashMap<>(2);
            data.put(BwSystemConstant.RESPONSE_ERROR_MESSAGE, e.getMessage());
            data.put(BwSystemConstant.TRACE, e.getStackTrace());
        }
        return new BwResponse(BwBasicExceptionEnum.LOCK_ERROR, data);
    }

    @ExceptionHandler(DataIntegrityViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BwResponse dataIntegrityViolationExceptionHandler(DataIntegrityViolationException e) {
        log.error("检测到数据库服务异常...");
        Map<String, Object> data = null;
        if (biWinProperties.getDebug()) {
            data = new HashMap<>(3);
            data.put(BwSystemConstant.RESPONSE_ERROR_MESSAGE, e.getMessage());
            data.put(BwSystemConstant.CAUSE,  e.getMostSpecificCause().getMessage());
            data.put(BwSystemConstant.TRACE, e.getStackTrace());
        }
        return new BwResponse(BwBasicExceptionEnum.DATABASE_ERROR, data);
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BwResponse allExceptionHandler(Exception e) {
        log.error("检测到系统异常...");
        Map<String, Object> data = null;
        if (biWinProperties.getDebug()) {
            // 最终按需调整 map 的初始化容器大小
            data = new HashMap<>(3);
            data.put(BwSystemConstant.RESPONSE_ERROR_MESSAGE, e.getMessage());
            data.put(BwSystemConstant.TRACE, e.getStackTrace());
            e.printStackTrace();
        }
        return new BwResponse(BwBasicExceptionEnum.SERVER_ERROR, data);
    }
}
